import { Action, getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators';

import { store } from '@/store';
import { getTenant } from '@/api/user';
import { getDomain } from '@/utils/util';
import { IUser } from '@/models/user.interface';

export interface IUserState {
  tenantId: string;
  userInfo: IUser;
}

@Module({ dynamic: true, namespaced: true, store, name: 'user' })
class User extends VuexModule implements IUserState {
  tenantId = '';
  userInfo = {} as IUser;

  @Mutation
  setTenantId(tenantId: string): void {
    this.tenantId = tenantId;
  }

  @Mutation
  setUserInfo(user?: IUser): void {
    this.userInfo = (user || {}) as IUser;
  }

  @Action
  async getTenant() {
    const domain = getDomain();
    const { data } = await getTenant(domain);
    const tenantId = data.data.tenantId || '000000';
    this.setTenantId(tenantId);
  }
}

export const userStore = getModule<User>(User);
